// components/u-authorize/index.js
const app = getApp();
Component({
	/**
	 * 组件的属性列表
	 */
	properties: {
		popupLoginShow: {
			type: Boolean,
			value: false
		},
	},

	/**
	 * 组件的初始数据
	 */
	data: {
		popupLoginShow: false,
		is_choose: true, // 是否选中协议
		auth: {
			avatar: '/static/icon/avatar.png',
			nickname: '临空文体'
		},
	},
	created() {
		let _that = this;
		_that.get_default_avatar();
	},
	/**
	 * 组件的方法列表
	 */
	methods: {
		onCancel() {
			var that = this;
			that.setData({
				popupLoginShow: false, //授权弹窗
			})
			that.triggerEvent('close');
		},
			// 获取默认头像
			get_default_avatar() {
				let that = this;
				app.post('defaultConfig', {}).then(res => {
					that.setData({
						auth: res.data
					})
				});
			},
				//更新头像
				onChooseAvatar(e) {
					const { avatarUrl } = e.detail
					app.uploadFile('uploadFileApi', {}, avatarUrl).then(res => {
					this.setData({
						['auth.avatar']: res.data.fullurl
					})
					})
				},

			// 设置昵称
			setNickname(e) {
				let _that = this;
				_that.setData({
					['auth.nickname']: e.detail.value,
				})
			},

			// 获取手机号
			authorizationPhone(e) {
				//先调用微信openid
				var that = this;
				let auth = that.data.auth
				if (e.detail.errMsg === 'getPhoneNumber:ok') {
					wx.login({
						success: function(res) {
							if (res.code) {
								let invite_id = app.getCache("mdkj_invite_id");
								app.post('wxLogin', {
									code: res.code,
									p_code:e.detail.code,
									invite_id:invite_id?invite_id:0,
									platform: 'wxmini',
									nickname:auth.nickname,
									avatar:auth.avatar
								}).then(l_res => {
									if (l_res.code == 1) {
										that.setData({
											popupLoginShow:false
										})
										let l_data = l_res.data;
										// 判断是否 已经登录过
										app.setCache('mdkj_token', l_data.userinfo.token);
										app.setCache('mdkj_userinfo', l_data.userinfo);
										app.Toast('登录成功')
										that.triggerEvent('onKeyEvent', l_data.userinfo);

									}else{
										app.Toast(l_res.msg)
									}
								})
							}else {
								app.Toast(res.msg || '授权失败')
							}
						}
					})
				} else {
					this.onCancel();
				}
			},

		//检查微信wx.login
		checkSession() {
			var that = this;
			wx.checkSession({
				success: function (res) {
					var openid = app.getCache('mdkj_openid');
					if (!wxLoginInfo) {
						that.wxLogin();
					} else {
						app.globalData.openid = openid;
					}
				},
				fail: (res) => {
					that.wxLogin();
				},
			})
		},
	}
})